package com.mystudy.jcu.semaphore;

import org.junit.Test;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * TODO: {@link Semaphore}
 * 当调用acquire方法的时候，获取到许可证才能调用，许可证的数量有限
 *
 * @author acy
 * @since 2019/06/19 14:28
 */
public class SemaphoreTest {
	public static void main(String[] args) {
		final SemaphoreLock lock = new SemaphoreLock();
		for (int i = 0; i < 2; i++) {
			new Thread(() -> {
				try {
					System.out.println(Thread.currentThread().getName() + "running");
					lock.lock();
					System.out.println(Thread.currentThread().getName() + "get the SemaphoreLock");
					TimeUnit.SECONDS.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unLock();
				}
				System.out.println(Thread.currentThread().getName() + "release the SemaphoreLock");
			}).start();
		}

	}

	static class SemaphoreLock {
		private final Semaphore semaphore = new Semaphore(1);

		public void lock() throws InterruptedException {
			semaphore.acquire();
		}

		public void unLock() {
			semaphore.release();
		}
	}
}
